<?php

class ShopInfoModule
{
	public function index()
	{
        global $_FANWE;

        $cate_id = intval($_GET['cate']);
        $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE cate_id = '.$cate_id.' AND status <>0';
        $r = FDB::fetchFirst($sql);
        if(!$r){
            fHeader('location: '.FU('index'));
            exit;
        }

        /*if($_FANWE['user']['reside_province'] > 0 && !isset($_GET['cityid']) && !isset($_GET['provinceid'])) {
            $cities = include './public/city.php';
            $cityname = $cities['all'][$_FANWE['user']['reside_city']]['name'];
            fHeader("location: /shopinfo.php?action=index&cate={$cate_id}&cityid={$_FANWE['user']['reside_city']}&areaname={$cityname}");
            exit;
        }*/

        $parent_id = $r['parent_id'] == 0 ? $cate_id : $r['parent_id'];
        $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE parent_id='.$parent_id . ' AND status!=0 ORDER BY sort ASC';
        $cates = FDB::fetchAll($sql);
        $cate_ids = array($cate_id);
        foreach($cates as $v) {
            $cate_ids[] = $v['cate_id'];
        }
        $where = 'notshow=0 AND cate_id IN('.($r['parent_id'] == 0 ? implode(',', $cate_ids) : $cate_id).')';

        $keywordsshow = array();
        $keywords = empty($r['search_keywords']) ? array() : explode(' ', $r['search_keywords']);
        $ids = empty($_GET['ids']) && $_GET['ids'] !== '0' ? array() : explode(',', $_GET['ids']);
        foreach($ids as $k => $id) {
            if(!is_numeric($id))
                unset($ids[$k]);
        }
        if(!empty($ids)) {
            $where .= ' AND (1';
            foreach($ids as $id) {
                if(isset($keywords[$id])) {
                    $where .= " AND name LIKE '%{$keywords[$id]}%'";
                    $keywordsshow[$id] = array('id' => $id, 'keyword' => $keywords[$id], 'checked' => true);
                }
            }
            $where .= ')';
        }
        foreach($keywords as $key => $v) {
            if(!isset($keywordsshow[$key])) {
                $keywordsshow[$key] = array('id' => $key, 'keyword' => $v, 'checked' => false);
            }
        }
        //地区
        if(isset($_SESSION['cityid']) && $r['parent_id'] == 0) $_GET['cityid'] = $_SESSION['cityid'];
        if(!empty($_GET['cityid'])) {
            $cityidarr = explode(',', $_GET['cityid']);
            foreach($cityidarr as $k => $v) {
                if(!is_numeric($v)) {
                    unset($cityidarr[$k]);
                }
            }
            if(!empty($cityidarr)) {
                $cityidstr = implode(',', $cityidarr);
                $where .= ' AND city IN('.$cityidstr.')';
            }
        } elseif(!empty($_GET['provinceid']) && is_numeric($_GET['provinceid'])) {
            $provinceid = intval($_GET['provinceid']);
            $where .= ' AND province='.$provinceid;
        }

        // V商家
        if(isset($_GET['vshop'])) {
            $where .= ' AND uid!=0';
        }

        if(!empty($_GET['areaname'])) {
            $areaname = htmlspecialchars($_GET['areaname']);
            $areanamearr = explode(',', $areaname);
        }

		$orderkeys = array('sharenum', 'commentnum', 'priceup', 'pricedown', 'bzj');
		$orders = array('sharenum' => 'share_num DESC', 'commentnum' => 'comment_count DESC', 'default' => 'orderby ASC,id DESC', 'bzj' => 'bzj DESC');
		$orderkey = in_array($_GET['order'], $orderkeys) ? $_GET['order'] : 'default';
		$order = $orders[$orderkey];

        $sql = 'SELECT COUNT(id) FROM '.FDB::table('wogu_user_shop').' WHERE '.$where;
        //echo $sql;exit;
        $count = FDB::resultFirst($sql);
        $page_args = array();
        $pager = buildPage('shopinfo/'.ACTION_NAME,$page_args,$count,$_FANWE['page'],10);
        $shop_list = array();
        if($_FANWE['page'] <= $pager['page']) {
            $pb_page_args = $page_args;
            $pb_page_args['page'] = $_FANWE['page'];
            $pb_page_args['pindex'] = '_pindex_';
            $pb_page_args['cate'] = $cate_id;
            $pb_page_args['order'] = $orderkey;
            if(!empty($_GET['ids'])) {
                $pb_page_args['ids'] = implode(',', $ids);
            }
            if(!empty($cityidarr)) {
                $pb_page_args['cityid'] = implode(',', $cityidarr);
            }elseif(!empty($_GET['provinceid']) && is_numeric($_GET['provinceid'])) {
                $pb_page_args['provinceid'] = $_GET['provinceid'];
            }
            $pb_url = $_FANWE['site_root'].'services/service.php?m=shopinfo&a=list&'.http_build_query($pb_page_args);
            if(isset($_GET['vshop'])) {
                $pb_url .= '&vshop';
            }
            $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop').' WHERE '.$where.' ORDER BY '.$order.' LIMIT '.$pager['limit'];
            $shop_list = FDB::fetchAll($sql);
            if(!empty($shop_list)){
                $cities = include './public/city.php';
                require FANWE_ROOT.'core/function/wogu.func.php';

                $uids = array();
                foreach ($shop_list as $key => $value) {
                    if(!$value['uid']) {
                        $uids[] = 1;
                    } else $uids[] = $value['uid'];

                    $shop_list[$key]['province_show'] = $cities['all'][$value['province']]['name'];
                    $shop_list[$key]['city_show'] = $cities['all'][$value['city']]['name'];
                    $shop_list[$key]['width'] = $shop_list[$key]['width'] > 0 ? $shop_list[$key]['width'] : 257;
                    $shop_list[$key]['height'] = $shop_list[$key]['height'] > 0 ? $shop_list[$key]['height'] : 172;
                    if(isset($_GET['ajax'])) {
                        $shop_list[$key]['img'] = create_mob_img($shop_list[$key]['img']);
                    }
                }

                $uids = array_unique($uids);
                $sql = 'SELECT * FROM '.FDB::table('user').' WHERE uid IN ('.implode(',', $uids).')';
                $tmp = FDB::fetchAll($sql);
                $name_list = array();
                foreach ($tmp as $key => $value) {
                    $name_list[$value['uid']] = $value['user_name'];
                }

                $sql = 'SELECT * FROM '.FDB::table('article').' WHERE uid IN ('.implode(',', $uids).') AND anli=1 AND isdefault=1';
                $res = FDB::query($sql);
                while($r = FDB::fetch($res)) {
                    $anli_list[$r['uid']] = $r;
                }
            }
            //tags
            $sql = 'SELECT tag_id FROM '.FDB::table('goods_category_tags').' WHERE cate_id='.$parent_id;
            $gctags = FDB::fetchAll($sql);
            $tagids = $tag_list = array();
            foreach($gctags as $v) {
                $tagids[] = $v['tag_id'];
            }
            if(!empty($tagids)) {
                $sql = 'SELECT * FROM '.FDB::table('goods_tags').' WHERE tag_id IN ('.implode(',', $tagids).')';
                $tag_list = FDB::fetchAll($sql);
            }
        }

        if(isset($_GET['ajax'])) {
            foreach ($shop_list as $k => $v) {
                if(isset($anli_list[$v['uid']])) {
                    $shop_list[$k]['anli'] = $anli_list[$v['uid']];
                }
            }

            echo json_encode(array(
                'list' => $shop_list,
                'count' => $count
            ));
        } else {
            //$_FANWE['nav_title'] = $r['seo_title'];
            //$_FANWE['seo_keywords'] = $r['seo_keywords'];
            //$_FANWE['seo_description'] = $r['seo_description'];
            include template('page/shopinfo/shopinfo_index');
            display();
            exit;
        }
	}

    public function show()
    {
        global $_FANWE;
        $id = $_FANWE['request']['id'];
        if(!is_numeric($id)){
            fHeader('location: '.FU('index'));
            exit;
        }

        $share_detail = FS('ShopInfo')->getShareDetail($id);
        if($share_detail['jb_num'] >= 100 || $share_detail['notshow']==1) {
            fHeader('location: /missing.html');
            exit;
        }

        $home_uid = $share_detail['uid'] == 0 ? 1 : $share_detail['uid'];
        $home_user = FS('User')->getUserById($home_uid);
        if(!$home_user['status']) {
            fHeader('location: /missing.html');
            exit;
        }

        // 实名认证信息
        $sql = 'SELECT * FROM '.FDB::table('wogu_realname_shop').' WHERE uid='.$share_detail['uid'];
        $realname = FDB::fetchFirst($sql);

        if($realname['stype'] == 1) {
            $sql = 'SELECT * FROM '.FDB::table('article').' WHERE uid='.$share_detail['uid'].' AND anli=1 AND isdefault=1';
            $anli = FDB::fetchFirst($sql);
        }

        $cities = include './public/city.php';
        $share_detail['province_show'] = $cities['all'][$share_detail['province']]['name'];
        $share_detail['city_show'] = $cities['all'][$share_detail['city']]['name'];

        //评论
		$share_detail['comments'] = FS('ShopInfo')->getShareCommentList($id,'0,10');
        $_FANWE['nav_title'] = $share_detail['name'];
        $_FANWE['seo_keywords'] = $share_detail['name'];
        $_FANWE['seo_description'] = $share_detail['seo_desc'];

		//分享评论分页
		$pager = buildPage('',array(),$share_detail['comment_count'],$_FANWE['page'],10);
		//评论数最多的
        $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop').' ORDER BY comment_count DESC LIMIT 3';
        $products_comment = FDB::fetchAll($sql);
		//转发最多的
        $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop').' ORDER BY share_num DESC LIMIT 3';
        $products_share = FDB::fetchAll($sql);

        // 实名认证信息
        $sql = 'SELECT * FROM '.FDB::table('wogu_realname_shop').' WHERE uid='.$share_detail['uid'];
        $realname = FDB::fetchFirst($sql);

        $currcate = $_FANWE['cache']['goods_category']['all'][$share_detail['cate_id']];
        $parentcate = $_FANWE['cache']['goods_category']['all'][$currcate['parent_id']];

        if(isset($_GET['ajax'])) {
            // BEGIN_评价
            $sql = 'SELECT id,comment,comment2,add_time,add_time2,grade,img1,img2,img3,img4,img5,img6,img7,img8,img9,userid FROM '.FDB::table('wogu_order').' WHERE shopid='.$share_detail['uid']." AND flag=4 AND comment!='' ORDER BY id DESC";
            $comments_tmp = FDB::fetchAll($sql);
            $comments = array();
            if(!empty($comments_tmp)) {
                foreach ($comments_tmp as $val) {
                    $uids[] = $val['userid'];
                }

                $uids = array_unique($uids);
                $users_tmp = FDB::fetchAll("SELECT avatar,uid,user_name FROM ".FDB::table('user')." WHERE uid IN(".implode(',', $uids).")");
                $users = array();
                foreach ($users_tmp as $v) {
                    $users[$v['uid']] = $v;
                }

                foreach ($comments_tmp as $val) {
                    $comment = array(
                        'id' => $val['id'],
                        'avatar' => avatar($users[$val['userid']]['avatar']),
                        'user_name' => $users[$val['userid']]['user_name'],
                        'comment' => $val['comment'],
                        'add_time' => date('y/m/d', strtotime($val['add_time'])),
                        'add_time2' => date('y/m/d', strtotime($val['add_time2'])),
                        'comment2' => $val['comment2'],
                        'grade' => $val['grade'],
                        'imgs' => array(),

                    );
                    for($i = 1; $i <= 9; $i++) {
                        if(!empty($val['img'.$i])) {
                            $comment['imgs'][] = trim($val['img'.$i], './');
                        }
                    }
                    $comments[] = $comment;
                }
            }
            // END_评价

            if($anli) {
                $share_detail['anli'] = $anli;
                $share_detail['price_show'] = $anli['price2'] > 0 ? $anli['price2'] : $anli['price'];
                $share_detail['puid'] = $home_user['uid'];
                $share_detail['puser_name'] = $home_user['user_name'];
            }

            $share_detail['content'] = str_replace('src="/ueditor/', 'src="'.$_FANWE['site_url'].'ueditor/', $share_detail['content']);
            $share_detail['content'] = str_replace('src="/public/', 'src="'.$_FANWE['site_url'].'public/', $share_detail['content']);
            $share_detail['lat'] = $realname['lat'];
            $share_detail['lng'] = $realname['lng'];
            $share_detail['comments'] = $comments;
            //var_dump($home_user);exit();
            exit(json_encode($share_detail));
        } else {
            include template('page/shopinfo/shopinfo_show');
            display();
            exit;
        }
    }

    public function jb() {
        global $_FANWE;

        $id = intval($_GET['id']);
        if($id) {
            $sql = 'UPDATE '.FDB::table('wogu_user_shop').' SET jb_num=jb_num+1 WHERE id='.$id;
            FDB::query($sql);
        }
        echo '举报成功';
    }
}
?>